<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Achievement_Model extends CI_Model {
	
	public function get_achievement_by_id($id) {
		$query = "SELECT * FROM smb_achievements WHERE id = ?";
		$result = $this->db->query($query, array($id));
		if ($result->num_rows() == 1) {
			return $result->row();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function count_achievement($username) {
		$query = "SELECT COUNT(*) AS sum FROM smb_achievements WHERE username = ?";
		$result = $this->db->query($query, array($username));
		if ($result->num_rows() == 1) {
			return $result->row()->sum;
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function get_achievement($username, $offset, $limit) {
		if ($offset == '' || $limit == '') {
			$query = "SELECT * FROM smb_achievements WHERE username = ? ORDER BY year DESC, name ASC";
			$result = $this->db->query($query, array($username));
		} else {
			$query = "SELECT * FROM smb_achievements WHERE username = ? ORDER BY year DESC, name ASC LIMIT ?, ?";
			$result = $this->db->query($query, array($username, intval($offset), intval($limit)));
		}
		if ($result->num_rows() > 0) {
			return $result->result();
		} else {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return NULL;
		}
	}
	
	public function add_achievement($username, $name, $year, $result) {
		$query = "INSERT INTO smb_achievements (id, username, name, year, result) VALUES (UUID(), ?, ?, ?, ?)";
		
		$this->db->trans_start();
		$this->db->query($query, array($username, $name, $year, $result));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	public function edit_achievement($id, $name, $year, $result) {
		$query = "UPDATE smb_achievements SET name = ?, year = ?, result = ? WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($name, $year, $result, $id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
			$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	public function delete_achievement($id) {
		$query = "DELETE FROM smb_achievements WHERE id = ?";
		
		$this->db->trans_start();
		$this->db->query($query, array($id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE) {
		$this->session->set_flashdata('error', 'Terjadi kesalahan saat akses database.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
}